<template>
  <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="项目名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入项目名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="项目类型" prop="typeId">
          <el-select v-model="queryParams.typeId" placeholder="请选择项目类型" clearable>
            <el-option
              v-for="dict in typeAllList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目地区" prop="areaId">
          <treeselect v-model="queryParams.areaId" style="width:300px;"
            :options="proviceList1"  placeholder="请选择项目地区" :load-options="loadOptions"/>
        </el-form-item>
        <el-form-item label="项目状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择项目状态" clearable>
            <el-option
              v-for="dict in dict.type.project_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <TableCard>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['cooperate:project:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              size="mini"
              @click="handleStatic"
            >项目数据统计
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

          <el-table :border="Global.tableShowBorder" v-loading="loading" :data="list">
            <el-table-column label="项目名称" align="center" prop="name"/>
            <el-table-column label="项目类型名称" align="center" prop="typeName"/>
            <el-table-column label="归属部门" align="center" prop="deptName"/>
            <el-table-column label="项目进度" align="center" prop="finishRate">
              <template slot-scope="{row}">
                <el-link v-if="ztFlag" :underline="false" type="primary" @click="handEidt(row,1)">{{row.finishRate}}</el-link>
                <span v-else>{{row.finishRate}}</span>
              </template>
            </el-table-column>
            <el-table-column label="项目状态" align="center" prop="status">
              <template slot-scope="{row}">
                <el-link v-if="ztFlag" :underline="false" type="primary" @click="handEidt(row,2)">
                  <dict-tag :options="dict.type.project_status" :value="row.status"/>
                </el-link>
                <dict-tag v-else :options="dict.type.project_status" :value="row.status"/>
              </template>
            </el-table-column>
            <el-table-column label="开始日期" align="center" prop="startDate"></el-table-column>
            <el-table-column label="结束日期" align="center" prop="endDate"></el-table-column>
            <el-table-column label="搁置原因" align="center" prop="shelvedReason" show-overflow-tooltip></el-table-column>
            <el-table-column label="终止原因" align="center" prop="abortedReason" show-overflow-tooltip></el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
              <template slot-scope="{row}">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(row)"
                  v-hasPermi="['cooperate:project:edit']"
                >修改
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(row)"
                  v-hasPermi="['cooperate:project:remove']"
                >删除
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  @click="handleUpdateRecode(row)"
                  v-hasPermi="['cooperate:projUpdRecDetail:list']"
                >修改记录
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
      </TableCard>
      <!-- 添加或修改对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
        <div v-if="title == '修改记录'">
          <el-form :model="xgQueryParams" ref="xgQueryForm" size="small" :inline="true"  label-width="108px">
            <el-form-item label="变更信息名称" prop="infoName">
              <el-input
                v-model="xgQueryParams.infoName"
                placeholder="请输入变更信息名称"
                clearable
                @keyup.enter.native="xgHandleQuery"
              />
            </el-form-item>
            <el-form-item label="类型" prop="category">
              <el-select v-model="xgQueryParams.category" placeholder="请选择类型" clearable>
                <el-option
                  v-for="dict in dict.type.project_edit_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="dateRange">
              <el-date-picker
                v-model="xgQueryParams.dateRange"
                type="datetimerange"
                range-separator="-"
                start-placeholder="开始日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00','23:59:59']"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="xgHandleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="xgResetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table :border="Global.tableShowBorder" v-loading="xgLoading" :data="xgRecod">
            <el-table-column label="原始值" align="center" prop="originalValue"/>
            <el-table-column label="新值" align="center" prop="newValue"/>
            <el-table-column label="变更信息名称" align="center" prop="infoName"/>
            <el-table-column label="类型" align="center" prop="category">
              <template slot-scope="{row}">
                <dict-tag :options="dict.type.project_edit_type" :value="row.category"/>
              </template>
            </el-table-column>
            <el-table-column label="创建者用户名" align="center" prop="createByName"/>
            <el-table-column label="创建者昵称" align="center" prop="createByNickName"/>
            <el-table-column label="创建时间" align="center" prop="createTime"/>
          </el-table>

          <pagination
            v-show="xgTotal>0"
            :total="xgTotal"
            :page.sync="xgQueryParams.pageNum"
            :limit.sync="xgQueryParams.pageSize"
            @pagination="listProjUpdRecDetail"
          />
        </div>
        <el-form v-else ref="form" :model="form" :rules="rules" label-width="120px">
          <div v-if="title == '修改项目状态' || title == '修改项目进度'">
            <div v-if="title == '修改项目状态'">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio :label="Number(item.value)" v-for="(item,index) in dict.type.project_status" :key="index">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="搁置原因" prop="shelvedReason" v-if="form.status == 3">
                <el-input v-model="form.shelvedReason" type="textarea" :rows="6" placeholder="请输入搁置原因"/>
              </el-form-item>
              <el-form-item label="终止原因" prop="abortedReason" v-if="form.status == 4">
                <el-input v-model="form.abortedReason" type="textarea" :rows="6" placeholder="请输入终止原因"/>
              </el-form-item>
              <el-form-item label="结束日期" prop="endDate">
                <el-date-picker
                  v-model="form.endDate"
                  type="date" value-format="yyyy-MM-dd"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </div>
            <div v-else>
              <el-form-item label="项目进度" prop="finishRate">
                <el-input-number v-model="form.finishRate" :precision="2" :step="1" :min="0" :max="100"></el-input-number>
              </el-form-item>
            </div>
          </div>
          <div v-else>
            <el-row>
              <el-col :span="24">
                <el-form-item label="项目名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入项目名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="省份" prop="provinceId">
                  <el-select v-model="form.provinceId" @change="proviceChange" clearable style="width: 200px;" placeholder="请选择">
                    <el-option
                      v-for="item in proviceList"
                      :key="item.id"
                      :label="item.extName"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="市"  prop="cityId">
                  <el-select v-model="form.cityId" @change="cityChange" style="width: 200px;" clearable placeholder="请选择">
                    <el-option
                      v-for="item in cityList"
                      :key="item.id"
                      :label="item.extName"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="区县" prop="countyId">
                  <el-select v-model="form.countyId" @change="countyChange" style="width: 200px;" clearable placeholder="请选择">
                    <el-option
                      v-for="item in countyList"
                      :key="item.id"
                      :label="item.extName"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="部门" prop="deptId">
                  <!-- :disable-branch-nodes="true" -->
                  <treeselect v-model="form.deptId" @select="bmChange"
                   :options="deptOptions" :disabled="form.id ? true : false" :show-count="true" placeholder="请选择部门"/>
                   <div><span style="color:red;">*</span>请选择类型为（部门）的数据</div>
                   <!-- <el-tree node-key="id" :data="deptOptions" :props="defaultProps" @node-click="handleNodeClick"></el-tree> -->
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目类型" prop="typeId">
                  <el-select v-model="form.typeId" :disabled="form.id ? true : false" filterable clearable placeholder="请选择项目类型">
                    <el-option
                      v-for="item1 in typeList"
                      :key="item1.typeId"
                      :label="item1.projectTypeName"
                      :value="item1.typeId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目负责人" prop="mastersId">
                  <el-select v-model="form.mastersId" multiple filterable clearable placeholder="请选择项目负责人">
                    <el-option
                      v-for="item1 in userList"
                      :key="item1.userId"
                      :label="item1.nickName"
                      :value="item1.userId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目协作者" prop="cooperationsId">
                  <el-select v-model="form.cooperationsId" multiple filterable clearable placeholder="请选择项目协作者">
                    <el-option
                      v-for="item1 in userList"
                      :key="item1.userId"
                      :label="item1.nickName"
                      :value="item1.userId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目描述信息" prop="note">
                  <el-input v-model="form.note" type="textarea" :rows="6" placeholder="请输入项目描述信息"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="时间选择" prop="dateRange">
                  <el-date-picker
                    v-model="form.dateRange"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="附件" prop="attachment"><el-button type="primary" icon="el-icon-plus" @click="addList('attachment')"></el-button></el-form-item>
            <el-row v-for="(item,index) in form.attachment" :key="index">
              <el-col :span="24">
                <el-form-item label="文件名称"
                :prop="'attachment.' + index + '.fileName'"
                :rules="{
                  required: true, message: '文件名称不能为空', trigger: 'blur'
                }">
                  <el-input v-model="item.fileName"  placeholder="请输入文件名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <!-- :prop="'attachment.' + index + '.url'"
                :rules="{
                  required: true, message: '文件路径不能为空', trigger: 'blur'
                }" -->
                <el-form-item label="文件路径"
                >
                  <div class="flex_hcneter">
                    <FileUpload :limit="1"  v-model="item.url"
                    :fileType="null" returnData="Array"
                    fileName="files" :fileData="{'bizType':'project',}"
                    action="/oa-pcapi/cooperate/file/uploadAtt" btnName="选择"></FileUpload>
                    <el-button style="margin-left:10px;"
                    @click="delList(index,'attachment')" type="primary" icon="el-icon-minus"></el-button>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" v-if="title != '修改记录'" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <el-dialog :title="tbTitle" :visible.sync="tbOpen" width="90%" append-to-body>
        <div class="flex_hcneter_bet">
          <div class="tongji_item flex_zhcenter flex_column" :style="{'background-color': item.bgcolor,}"
          v-for="(item,index) in diquList" :key="index">
            <div class="value txt-ellipsis">{{item.value}}</div>
            <div class="itles">{{item.label}}</div>
          </div>
        </div>
        <div class="flex_hcneter_bet">
          <h2>项目数量分布</h2>
          <el-radio-group v-model="areaIndex" style="margin-bottom: 30px;" @change="areaChange">
            <el-radio-button v-for="(item,index) in diquList" :key="index" :label="item.key">{{item.label}}</el-radio-button>
          </el-radio-group>
        </div>
        <div>
          <div ref="areaStatic" style="height:450px;width:100%;"></div>
        </div>
       
        <div slot="footer" class="dialog-footer">
          <el-button @click="tbOpen = false">取 消</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
import {listProject, getProject, addProject, updateProject, delProject,editFinishRate,editStatus,selectAllProjCount,} from "@/api/collaWorryFree/project";
import {listArea,selectProjAreaCounts} from "@/api/collaWorryFree/region";
import {deptUserList, } from "@/api/system/user";
import {getListByDeptId,} from "@/api/collaWorryFree/departProjectPerm";
import {listProjUpdRecDetail,} from "@/api/collaWorryFree/projectRelatPer";
import {listAllProjectType,} from "@/api/collaWorryFree/projectType";
import {treeselect,getUserDeptTree} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { aW } from '@fullcalendar/core/internal-common';
export default {
  name: "Project",
  dicts: ['project_status','project_edit_type',],
  components: {Treeselect},
  data() {
    return {
      areaIndex:1,//选中下表
      diquList:[
        {label:'省份',value:0,bgcolor:'#E7F4FE',prop:'totalProvinceNum',key:1,},{label:'城市',value:0,bgcolor:'#ECFEEF',prop:'totalCityNum',key:2,},
        {label:'县区',value:0,bgcolor:'#F1E4E4',prop:'totalCountyNum',key:3,},
      ],
      formDetail:[
        {label:'总省份数量',prop:'totalProvinceNum',},{label:'总城市数量',prop:'totalCityNum',},{label:'总县区数量',prop:'totalCountyNum',},
        {label:'省份项目数量分布列表',prop:'provinceList',isCustom:true,span:24,list:true,},{label:'城市项目数量分布列表',prop:'cityList',isCustom:true,span:24,list:true,},
        {label:'县区项目数量分布列表',prop:'countyList',isCustom:true,span:24,list:true,},
      ],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 遮罩层
      loading: true,
      xgLoading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      xgTotal: 0,
      // 表格数据
      list: [],
      // 弹出层标题
      title: "",
      tbTitle: "",
      // 是否显示弹出层
      open: false,
      tbOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,name:null,typeId:null,
        dateRange: [],areaId:null,status:null,
      },
      xgQueryParams: {
        pageNum: 1,
        pageSize: 10,dateRange: [],infoName: null,category: null,
      },
      tbQueryParams: {},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [ {required: true, message: "项目名称不能为空", trigger: "blur"} ],
        typeId: [ {required: true, message: "项目类型不能为空", trigger: "change"} ],
        deptId: [ {required: true, message: "归属部门不能为空", trigger: "change"} ],
        mastersId: [ {required: true, message: "项目负责人不能为空", trigger: "change"} ],
        dateRange: [ {required: true, message: "时间选择不能为空", trigger: "change"} ],
        status: [ {required: true, message: "项目状态不能为空", trigger: "change"} ],
        finishRate: [ {required: true, message: "项目进度不能为空", trigger: "blur"} ],
      },
      deptOptions:[],//部门数据
      userList:[],//用户数据
      typeList:[],//根据部门获取类型数据
      xgRecod:[],//修改记录数据
      typeAllList:[],//所有类型数据
      ztPermission:'cooperate:project:edit',//修改状态权限和修改进度权限
      ztFlag:false,//修改状态权限和修改进度权限显示
      bumenObj:{},
      proviceList1:[],//省数据
      proviceList:[],//省数据
      cityList:[],//市数据
      countyList:[],//区县数据
    };
  },
  created() {
    const user = this.$store.state.user
    const permissions = user.permissions
    const flag = !!permissions.find(item => item == this.ztPermission)
    if (flag || permissions[0] == '*:*:*') this.ztFlag = true
    this.selectProjAreaCounts(0,1)
    this.listAllProjectType()
    this.getList();
  },
  methods: {
    areaChange(e){//地区他爸改变
      let list = []
      if( e == 1) list = this.form.provinceList || []
      if( e == 2) list = this.form.cityList || []
      if( e == 3) list = this.form.countyList || []
      this.getAreaStatic(list)
    },
    getAreaStatic(list){//折线柱状混合图
      this.chart = this.$echarts.init(this.$refs.areaStatic)
      let nameList = []
      let numList = []
      list.map(item=>{
        nameList.push(item.name || '')
        numList.push(item.num || 0)
      })
      this.chart.setOption({
        color:["#3B82F6",],
        tooltip: {
          trigger: 'axis',
          formatter:(params)=> {
            let str = ``;
            // console.log('params',params)
            params.forEach((item, idx) => {
              str += `${item.seriesName}<br/>`
              str += `${item.marker}${item.name}: ${item.data}`
              str += idx === params.length -1? '': '<br/>'
            })

            return str;
          },
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend:{
          left: 'center',
          bottom: '0',
        },
        grid: {
          left: '0',
          right: '0',
          height: '85%',
          bottom: '8%',
          backgroundColor: 'white',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: nameList,
            axisLabel: {
              show: true,
              textStyle: {
                color: "#333",
              },
            },
          }
        ],
        // {
        //   type: 'category',
        //   data: nameList
        // },
        yAxis: [
          {
            type: 'value',
            name: '项目数量分布',
            min: 0,
            axisLabel: {
              show: true,
              formatter: '{value}',
              textStyle: {
                color: "#333",
              },
            },
          },
        ],
        // dataZoom:[
        //   {
        //     type: 'slider',
        //     show: true,
        //     // 设置背景颜色
        //     backgroundColor: "#F1F1F1",
        //     // 设置选中范围的填充颜色
        //     fillerColor: "#A8A8A8",
        //     // 设置边框颜色
        //     borderColor: "#A8A8A8",
        //     // 是否显示detail，即拖拽时候显示详细数值信息
        //     showDetail: false,
        //     xAxisIndex: [0],
        //     bottom: 10,
        //     handleSize: 2,
        //     height: '13px',
        //     start: 0,
        //     end: this.computedPosition(9,xArraylength),
        //   },
        //   {
        //     type: 'inside',
        //     start: 40,
        //     end: 100
        //   },
        //   {
        //     type: 'slider',
        //     show: false,
        //     yAxisIndex: 0,
        //     filterMode: 'empty',
        //     width: 3,
        //     height: '70%',
        //     handleSize: 2,
        //     showDataShadow: false,
        //     left: '93%'
        //   },
        //   {
        //       // 没有下面这块的话，只能拖动滚动条，
        //       // 鼠标滚轮在区域内不能控制外部滚动条
        //       type: "inside",
        //       // 滚轮是否触发缩放
        //       zoomOnMouseWheel: false,
        //       // 鼠标滚轮触发滚动
        //       moveOnMouseMove: false,
        //       moveOnMouseWheel: false,
        //   },
        // ],
        series: [
          {name: "项目数量分布",type: "bar",data: numList,},
        ],
      })
    },
    async loadOptions({ action, parentNode, callback }) {//地区选择数据加载
      console.log(action, parentNode, callback )
      if (action === 'LOAD_CHILDREN_OPTIONS') {
        const children = await this.selectProjAreaCounts(parentNode.id,parentNode.pid === 0 ? 2 : 3)
        console.log('children',children)
        if(children.length) parentNode.children = children
        callback()
      }
    },
    async selectProjAreaCounts(pid,type){//获取行政区划信息
      let res = await selectProjAreaCounts(pid)
      let data = res.data || []
      data = data.map(item=>{
        let obj = {...item,label:item.name + `（${item.num}）`,}
        if(type !== 3) obj.children = null
        return obj
      })
      if(type === 1) this.proviceList1 = data
      return data
    },
    handleStatic(){//项目数据统计
      this.tbTitle = '项目数据统计'
      this.tbOpen = true
      this.areaIndex = 1
      this.selectAllProjCount()
    },
    async selectAllProjCount(){//获取项目数据统计
      let res = await selectAllProjCount()
      let data = res.data || {}
      this.form ={...data}
      this.diquList = this.diquList.map(item=>{
        return {
          ...item,value:data[item.prop],
        }
      })
      this.getAreaStatic(data.provinceList || [])
    },
    proviceChange(e){// 省份下拉改变
      let form = {...this.form}
      let obj = this.proviceList.find(item=>item.id == e)
      form.provinceName = obj ? obj.extName : ''
    	form.cityId = ''
    	form.countyId = ''
      this.form = {...form}
      this.cityList = []
      this.countyList = []
      if(!e) return
    	this.listArea(e,2)
    },
    cityChange(e) {// 城市下拉改变
      let form = {...this.form}
      let obj = this.cityList.find(item=>item.id == e)
      form.cityName = obj ? obj.extName : ''
      form.countyId = ''
      this.form = {...form}
      this.countyList = []
      if(!e) return
    	this.listArea(e,3)
    },
    countyChange(e){// 城市下拉改变
      let form = {...this.form}
      let obj = this.countyList.find(item=>item.id == e)
      form.countyName = obj ? obj.extName : ''
      this.form = {...form}
    },
    async listArea(pid,type){//获取行政区划信息
      let res = await listArea(pid)
      let rows = res.rows || []
      if(type === 1) this.proviceList = rows
      if(type === 2) this.cityList = rows
      if(type === 3) this.countyList = rows
    },
    handleNodeClick(Node){//
      console.log(Node)
    },
    addList(ziduan){//添加列表
      this.form[ziduan].push({})
    },
    delList(index,ziduan){//删除列表
      this.form[ziduan].splice(index,1)
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      getUserDeptTree().then(response => {
        let data = response.data || []
        this.deptOptions = [...data]
        this.getChart(this.deptOptions)
      });
    },
    getChart(data){//阶梯处理部门下拉数据
      data.forEach((item,index) => {
        item.id = item.deptId
        item.label = item.deptName + `(${item.deptType == 2 ? '部门' : (item.deptType == 3 ? '组别' : '公司')})`
        let children = item.children || []
        if(children.length ) {
          this.getChart(item.children)
        }else{
          delete item.children
        }
      });
    },
    bmChange(e){//部门改变
      console.log(e)
      this.bumenObj = {...e}
      if(e.id == this.form.deptId) return
      let form = {...this.form}
      this.getPdbumenType(e.deptType)
      form.typeId = null
      form.mastersId = null
      form.cooperationsId = null
      this.form = {...form}
      this.deptUserList(e.id)
      this.getListByDeptId(e.id)
    },
    getPdbumenType(deptType){//判断部门类型是否为部门选项
      let flag = deptType == 1 ? true : false
      if(flag) this.$modal.msgError("请选择名称右侧部门类型为（部门或者组别）的数据");
      return flag
    },
    async deptUserList(deptId){//获取部门下用户
      let res = await deptUserList({deptId})
      let data = res.data || []
      this.userList = data
    },
    async getListByDeptId(deptId){//获取部门下类型
      let res = await getListByDeptId({deptId})
      let data = res.data || []
      this.typeList = data
    },
    async listAllProjectType(){//查询所有项目类型列表
      let res = await listAllProjectType()
      let data = res.data || []
      this.typeAllList = data
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      let queryParams = {...this.queryParams}
      let dateRange = queryParams.dateRange || []
      if(dateRange.length) {
        queryParams.startDate = dateRange[0]
        queryParams.endDate = dateRange[1]
      }
      delete queryParams.dateRange
      listProject(queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      // this.reset();
    },
    // 表单重置
    reset() {
      this.form = {attachment:[{}],};
      // this.resetForm("form");
      this.userList = []
      this.typeList = []
      this.listArea(0,1)
      this.cityList = []
      this.countyList = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目";
      this.getTreeselect()
    },
    handleUpdateRecode(row) {//修改记录
      this.open = true;
      this.title = "修改记录";
      this.xgQueryParams.projectId = row.id
      this.xgResetQuery()
    },
    async listProjUpdRecDetail(){//查询项目信息修改记录明细列表
      this.xgLoading = true;
      let queryParams = {...this.xgQueryParams}
      let dateRange = queryParams.dateRange || []
      if(dateRange.length) {
        queryParams.createStart = dateRange[0]
        queryParams.createEnd = dateRange[1]
      }
      delete queryParams.dateRange
      let res = await listProjUpdRecDetail(queryParams)
      let rows = res.rows || []
      this.xgRecod = rows
      this.xgTotal = res.total || 0
      this.xgLoading = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id
      getProject(id).then(response => {
        let data = response.data || {};
        let masters = data.masters || []
        let cooperations = data.cooperations || []
        this.form = {
          ...data,dateRange: data.startDate ? [data.startDate,data.endDate] : [],
          mastersId:masters.map(item=>item.userId),
          cooperationsId:cooperations.map(item=>item.userId),
          attachment:data.attachment || [{}],
        }
        this.open = true;
        this.title = "修改项目";
        this.deptUserList(data.deptId)
        this.getListByDeptId(data.deptId)
        this.getTreeselect()
        if(data.provinceId) this.listArea(data.provinceId,2)
        if(data.cityId) this.listArea(data.cityId,3)
      });
    },
    handEidt(row,type){//修改状态和进度
      this.reset();
      this.open = true;
      this.title = type == 2 ? '修改项目状态' : "修改项目进度";
      let form = {...this.form}
      form.id = row.id
      if(type == 2) {
        form.status = row.status
      }else{
        form.finishRate = row.finishRate
      }
      this.form = {...form}
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let form = {...this.form}
          if(this.title == '修改项目状态' || this.title == '修改项目进度'){
            let api = this.title == '修改项目状态' ? editStatus : editFinishRate
            api(form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          }else{
            let dateRange = form.dateRange || []
            if(dateRange.length) {
              form.startDate = dateRange[0]
              form.endDate = dateRange[1]
            }
            let flag = this.getPdbumenType(this.bumenObj.deptType)
            if(flag) return
            if (this.form.id != undefined) {
              updateProject(form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addProject(form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row,type) {
      const id = row.id
      this.$modal.confirm('是否确认删除该数据项？').then(function () {
          return delProject(id);
      }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 搜索按钮操作 */
    xgHandleQuery() {
      this.xgQueryParams.pageNum = 1;
      this.listProjUpdRecDetail();
    },
    /** 重置按钮操作 */
    xgResetQuery() {
      this.resetForm("xgQueryForm");
      this.xgHandleQuery();
    },
  }
};
</script>
<style scoped lang="scss">
.tongji_item{
  width: 30%;height: 10%;border-radius: 5px;margin-bottom: 15px;
  box-sizing: border-box;padding: 25px 10px;
  .itles{margin-top: 30px;font-size: 24px;}
  .value{font-size: 35px;}
}
</style>